#define _CRT_SECURE_NO_WARNINGS
#include"SList.h"

ListNode* BuyLTNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

ListNode* ListCreate()
{
	ListNode* pHead = BuyLTNode(-1);
	pHead->next = pHead;
	pHead->prev = pHead;
	return pHead;
}



void ListDestroy(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(pHead);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		printf("%d<<=>>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void LTInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newnode = BuyLTNode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	LTInsert(pHead, x);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	LTInsert(pHead->next, x);
}

void LisrErase(ListNode* pos)
{
	assert(pos);
	ListNode* posprev = pos->prev;
	ListNode* posnext = pos->next;
	posprev->next = posnext;
	posnext->prev = posprev;
	free(pos);
}

bool LTEmpty(ListNode* pHead)
{
	assert(pHead);
	return pHead->next == pHead;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(!LTEmpty(pHead));
	LisrErase(pHead->prev);
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!LTEmpty(pHead));
	LisrErase(pHead->next);
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}